package cn.ydxiaoshuai.workrecord;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author 小帅丶
 * @className DocToPDFSample
 * @Description DOC文档转PDF
 * @Date 2021-07-08-11:55
 **/
@Slf4j
public class DocToPDFSample {

    public static boolean getLicense() {
        boolean result = false;
        try {
            //license.xml
            File file = new File("src/main/resources/libs/license.xml");
            InputStream is = new FileInputStream(file);
            License asposeLic = new License();
            asposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            log.info("getLicense() 出错了\t{}", e.getMessage());
        }
        return result;
    }

    public static void doc2pdf(String inPath, String outPath) {
        // License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            log.info("License错误");
        } else {
            FileOutputStream os = null;
            try {
                long startTime = System.currentTimeMillis();
                // 新建一个空白pdf文档
                File file = new File(outPath);
                os = new FileOutputStream(file);
                // Address是将要被转化的word文档
                Document doc = new Document(inPath);
                // 支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
                doc.save(os, SaveFormat.PDF);
                // EPUB, XPS, SWF 相互转换
                long endTime = System.currentTimeMillis();
                // 转化用时
                log.info("DOC转换PDF成功，共耗时(毫秒)：{}", (endTime - startTime));
            } catch (Exception e) {
                log.info("doc2pdf() 出错了\t{}", e.getMessage());
            } finally {
                if (os != null) {
                    try {
                        os.flush();
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
